<script lang="ts" setup>
import { ref, reactive, watch, toRefs } from "vue"
import { CirclePlus, RefreshRight, Search, Refresh } from "@element-plus/icons-vue"
// import { CirclePlus, RefreshRight, UploadFilled } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
// import { formatDateTime } from "@/utils"
import { shortcuts } from "@/utils/dateSet"
import { ElMessage, type FormInstance } from "element-plus"
// const fileList = ref<any>([])
import { createGrabDataApi, createGrabDataApi1, updateGrabDataApi, getGrabDataApi } from "@/api/role"
import { getComboSourceDataApi } from "@/api/combo-source"

defineOptions({
  name: "grapOrderSet"
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const loading = ref<boolean>(false)
//#region 增
const dialogVisible = ref<boolean>(false)
const dialogVisible1 = ref<boolean>(false)
const timesArry = ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])
const DATA = reactive<any>({
  formData: {},
  formData1: {},
  formRules: {
    superName: [{ required: true, message: "请输入上级名称", trigger: "blur" }],
    superId: [{ required: true, message: "请输入上级编码", trigger: "blur" }],
    times: [{ required: true, message: "请选择时间", trigger: "blur" }],
    number: [{ required: true, message: "请填写每小时重提数", trigger: "blur" }]
  },
  formRules1: {
    superName: [{ required: true, message: "请输入上级名称", trigger: "blur" }],
    superId: [{ required: true, message: "请输入上级编码", trigger: "blur" }]
  }
})
const { formData, formData1, formRules, formRules1 } = toRefs(DATA)
const tableDataComboSource = ref<any>([])
const getComboSource = () => {
  getComboSourceDataApi({
    page: 1,
    size: 300
  }).then((res: any) => {
    if (res.code == 200) {
      tableDataComboSource.value = res.data.list
    }
  })
}
getComboSource()
const handleCreate = () => {
  if (!formData.value.times) {
    formData.value.times = []
  }
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        createGrabDataApi({
          ...formData.value,
          times: formData.value.times.join(",")
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        updateGrabDataApi({
          ...formData.value,
          times: formData.value.times.join(",")
        }).then(() => {
          ElMessage.success("修改成功")
          console.log("修改")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
const handleCreate1 = () => {
  formRef1.value?.validate((valid: boolean) => {
    if (valid) {
      createGrabDataApi1({
        ...formData1.value,
        startTime: formData1.value.searchDate[0],
        endTime: formData1.value.searchDate[1]
      }).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success("成功")
        }
      })
    }
  })
}
//清除查询日期
const clearDate = (val: any) => {
  // console.log(val)
  if (!val) {
    formData1.value.searchDate = []
  }
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  dialogVisible.value = true
  currentUpdateId.value = row.id
  formData.value = JSON.parse(JSON.stringify(row))
  formData.value.times = row.times.split(",")
}
//#endregion

// #region 搜索
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  superName: ""
})
// 查询按键
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

// 重置按键
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

//#region 查
const tableData = ref<any>([])
const getTableData = () => {
  loading.value = true
  getGrabDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    ...searchData
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

// 刷新数据
const handleRefresh = () => {
  getTableData()
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
//#endregion

// #region 清除验证  清除规则报错信息
const formRef = ref<FormInstance | null>(null)
const formRef1 = ref<FormInstance | null>(null)
const clearValidateA = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
  formRef1.value?.clearValidate()
  formRef1.value?.resetFields()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidateA()
  // 清空reactive对象里面的key值
  Object.keys(formData.value).map((key) => {
    delete formData.value[key]
  })
  Object.keys(formData1.value).map((key) => {
    delete formData1.value[key]
  })
}
const defaultTime = new Date(2000, 1, 1, 0, 0, 0)
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="superName" label="上级名称">
          <!-- <el-input v-model.trim="searchData.superName" placeholder="请输入" /> -->
          <el-select v-model="searchData.superName" filterable clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in tableDataComboSource" :key="item.name" :value="item.name" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加0点抢单</el-button>
          <el-button type="success" @click="dialogVisible1 = true">手动抢单</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="superName" label="上级名称" align="center" />
          <el-table-column prop="superId" label="上级编码" align="center" />
          <el-table-column prop="number" label="每小时重提数" align="center" />
          <el-table-column prop="status" label="是否开启" align="center">
            <template #default="scope">
              <span v-if="scope.row.status == 1">是</span>
              <span v-if="scope.row.status == 0">否</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增 修改 -->
    <el-dialog class="inputdialog" v-model="dialogVisible" title="新增" @close="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="superName" label="上级名称">
          <el-select v-model="formData.superName" filterable clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in tableDataComboSource" :key="item.name" :value="item.name" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="superId" label="上级编码">
          <el-input v-model="formData.superId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="number" label="每小时重提">
          <el-input v-model="formData.number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="times" label="重提时间">
          <el-select v-model="formData.times" filterable clearable multiple placeholder="请选择" style="width: 240px">
            <el-option v-for="item in timesArry" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="是否开启">
          <el-select v-model="formData.status" clearable placeholder="请选择" style="width: 240px">
            <el-option key="02110" label="是" :value="1" />
            <el-option key="02111" label="否" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交</el-button>
      </template>
    </el-dialog>
    <!-- 手动抢单 -->
    <el-dialog class="inputdialog" v-model="dialogVisible1" title="手动抢单" @close="resetForm" width="60%">
      <el-form ref="formRef1" :model="formData1" :rules="formRules1" label-width="100px" label-position="left">
        <el-form-item prop="superName" label="上级名称">
          <el-select v-model="formData1.superName" filterable clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in tableDataComboSource" :key="item.name" :value="item.name" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="superId" label="上级编码">
          <el-input v-model="formData1.superId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="number" label="每小时重提数">
          <el-input v-model="formData1.number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="searchDate" label="抢单时间" style="width: 600px">
          <el-date-picker
            v-model="formData1.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime"
            @change="clearDate"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="handleCreate1">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.Signature-matter {
  margin-bottom: 20px;
  border: 1px solid #6cf;
  background: #e5f0ff;
  padding: 10px 14px;
  border-radius: 5px;
  font-size: 12px;
}
:deep(.el-radio-group) {
  display: block;
}
:deep(.el-radio.el-radio--large) {
  display: block !important;
}
</style>
